package com.csproj.basic.resource;

import com.codahale.metrics.annotation.Timed;
import com.csproj.basic.service.ContainerService;
import com.csproj.basic.service.dto.ContainerDTO;
import com.csproj.basic.service.dto.WarehouseDTO;
import com.csproj.siiat.base.common.dto.BaseDTO;
import com.csproj.siiat.base.common.repository.PageableTools;
import com.csproj.system.domain.UserInfo;
import com.csproj.system.service.SysLogsService;
import com.csproj.system.service.UserInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * REST controller for managing Container.
 */
/**
 * 集装箱管理的resource
 *
 *  TODO action、service都秉承返回是什么资源就在那个资源的aciton、service里面写（比如查看uid=3的机构信息）
 *  TODO url定义遵循/api/gateway（服务名）/v1/资源名
 *  TODO 定义rap要理解资源的概念（比如图书馆的书和我借的书）
 *
 *  TODO action方法只负责控制调用，不处理具体业务。
 */
@RestController
@RequestMapping("/api/siiat/v1")
public class ContainerResource {

    private final Logger log = LoggerFactory.getLogger(ContainerResource.class);

    private static final String ENTITY_NAME = "container";

    private final ContainerService containerService;
    private final UserInfoService userInfoService;
    private final SysLogsService sysLogsService;

    public ContainerResource(ContainerService containerService,UserInfoService userInfoService,SysLogsService sysLogsService) {
        this.containerService = containerService;
        this.sysLogsService = sysLogsService;
        this.userInfoService = userInfoService;
    }

    /**
     * POST  /container : 创建集装箱
     * @param containerDTO 集装箱DTO
     * @return
     * TODO 保存post方法
     * TODO 每个方面里面都要加try catch处理
     */
    @PostMapping("/container")
    @Timed
    public BaseDTO createContainer(@Valid @RequestBody ContainerDTO containerDTO){
        ContainerDTO result = containerService.saveAndGetDTO(containerDTO);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_create_container","");
        return BaseDTO.createBaseDTO().setData(result);
    }


    /**
     * PUT  /container : 修改集装箱.
     * @param containerDTO 企业集装箱.DTO
     * @return
     */
    @PutMapping("/container/{id}")
    @Timed
    public BaseDTO updateContainer(@Valid @RequestBody ContainerDTO containerDTO, @PathVariable String id) throws URISyntaxException {
        containerDTO.setId(id);
        ContainerDTO result = containerService.updateAndGetDTO(containerDTO);
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_update_container","");
        return BaseDTO.createBaseDTO().setData(result);
    }

    /**
     * GET  /container : 获取集装箱.
     * @return 集装箱信息
     */
    @GetMapping("/container/all")
    @Timed
    public BaseDTO getAllContainerDTO() {
        List<ContainerDTO> lists = containerService.findAllAndGetDTO();
        return BaseDTO.createBaseDTO().setFieldList(lists);
    }

    /**
     * GET  /container : 获取集装箱信息.
     * @return 集装箱信息
     */
    @GetMapping("/container")
    @Timed
    public BaseDTO getPageContainers(@RequestParam(value = "pageNumber",required = false) Integer pageNum,
                                        @RequestParam(value = "pageSize",required = false) Integer pageSize,
                                        @RequestParam(value = "name",required = false) String name,
                                     @RequestParam(value = "companyId",required = false) String companyId
                                     ) {
        Pageable pageable = PageableTools.basicPage(pageNum,pageSize);
        Map<String,Object> map = new HashMap<>();
        map.put("containerNo",name);
        map.put("containerCompanyId",companyId);
        BaseDTO result = containerService.findPageListAndGetDTO(map,pageable);

        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_view_container_list","");
        return result;
    }

    /**
     * GET  /container/:id : 根据集装箱id，获取集装箱信息
     *
     * @param id 集装箱id
     * @return 集装箱信息
     */
    @GetMapping("/container/{id}")
    @Timed
    public BaseDTO getContainer(@PathVariable String id) {
        ContainerDTO containerDTO = containerService.findOneAndGetDTO(id);
        return BaseDTO.createBaseDTO().setData(containerDTO);
    }

    /**
     * DELETE  /container/:id : 根据id，删除集装箱.
     * @param id id
     * @return
     */
    @DeleteMapping("/container/{id}")
    @Timed
    public BaseDTO deleteContainer(@PathVariable String id) {
        containerService.delete(id);
        return BaseDTO.createBaseDTO().setMessage("delete_success");
    }

    /**
     * 根据集装箱ids，批量删除集装箱
     * @param ids ids
     * @return
     */
    @DeleteMapping("/container/deleteContainers")
    @Timed
    public BaseDTO deleteIds(@RequestBody(required = false) String[] ids) {
        containerService.deleteIds(ids);
        return BaseDTO.createBaseDTO().setMessage("batch_delete_success");
    }

    /**
     * 上传文件
     * @param file file
     * @return
     */
    @PostMapping("/container/uploadFile")
    @Timed
    public BaseDTO uploadFile(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        String filePath = containerService.uploadFile(request,file);
        Map<String,Object> map = new HashMap<>();
        map.put("url",filePath);
        return BaseDTO.createBaseDTO(map).setMessage("upload_file_success");
    }

    /**
     * 批量导入
     * @Param file
     */
    @PostMapping("/container/batchImport")
    @Timed
    public BaseDTO containerBatchImport(MultipartFile file){
        UserInfo userInfo = userInfoService.getCurrentUser();
        sysLogsService.saveForGet("", userInfo.getName()+":user_batch_import_container_list","");
        return containerService.batchImport(file);
    }
}